package com.tender.desensitization.factory.instance;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import com.tender.desensitization.filter.SensitiveFieldFilter;
import com.tender.desensitization.FieldReflectUtils;

import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;
import com.tender.desensitization.annotations.SensitiveField;
import com.tender.desensitization.enums.SensitiveEnum;
import java.util.stream.IntStream;
import com.tender.desensitization.filter.FieldFilter;
import com.tender.utils.AESUtil;

@Slf4j
public class UnSensitiveUserWrapperProcessFactory extends AbstractUserWrapperProcessFactory {

    public UnSensitiveUserWrapperProcessFactory(TypeProcessFactoryFacade factoryFacade) {
        super(factoryFacade, new SensitiveFieldFilter());
    }

    @Override
    public Object processType(Object instance) {
        if (null == instance) {
            return null;
        }

        // 处理用户自定义的包装类
        List<Field> allFields = FieldReflectUtils.getAllFields(instance.getClass());

        for (Field field : allFields) {
            field.setAccessible(true);
            TypeProcessFactory processFactory = getFactoryFacade().getProcessFactory(field.getType());
            if (null != processFactory) {
                try {
                    processFactory.processType(field.get(instance));
                } catch (Exception e) {
                    log.error("******************************************");
                    log.error("【获取值，反射异常】field name：{}, 原始对象：{}，具体异常为：", field.getName(), instance, e);
                    log.error("******************************************");
                }
            } else {
                // 基本数据类型 or String.class 类型
                List<FieldFilter> collect = getIncludeTypeFilters().stream().filter(item -> item.isMatch(field)).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(collect) && String.class == field.getType()) {
                    String originalValue = "";
                    try {
                        originalValue = (String) field.get(instance);
                        String processedValue = doProcessFieldValue(originalValue, field.getAnnotation(SensitiveField.class));
                        field.set(instance, processedValue);
                    } catch (Exception e) {
                        log.error("******************************************");
                        log.error("【获取值，反射异常】field name：{}, 原始对象：{}，具体异常为：", field.getName(), instance, e);
                        log.error("******************************************");
                    }
                }
            }
        }

        return instance;
    }

    /**
     * 脱敏处理
     */
    private String doProcessFieldValue(String value, SensitiveField sensitiveField) {
        if (StringUtils.isBlank(value)) {
            return "";
        }

        // 手机号码脱敏逻辑，将中间四位替换为 *****
        if (value.length() == 11 && sensitiveField.value().equals(SensitiveEnum.PHONE_NO)) {
            return value.substring(0, 3) + "****" + value.substring(7);
        } else if (sensitiveField.value().equals(SensitiveEnum.ID_CARD_NO)) {
            if (value.length() == 15) {
                // 123456 789abc def
                return value.substring(0, 6) + "*****" + value.substring(12);
            } else if (value.length() == 18) {
                // 123456 789abcdef ghi
                return value.substring(0, 6) + "********" + value.substring(15);
            } else if (value.length() > 18) {
                value = AESUtil.decrypt(value);
                if (StringUtils.isNotBlank(value)) {
                    if (value.length() == 15) {
                        // 123456 789abc def
                        return value.substring(0, 6) + "*****" + value.substring(12);
                    } else if (value.length() == 18) {
                        // 123456 789abcdef ghi
                        return value.substring(0, 6) + "********" + value.substring(15);
                    }
                }
            }
        } else if (sensitiveField.value().equals(SensitiveEnum.USERNAME)) {
            // 姓名脱敏
            int length = value.length();
            StringBuilder sb = new StringBuilder();
            IntStream.range(0, length - 1).forEach(item -> sb.append("*"));
            return value.substring(0, 1) + sb;
        }

        return value;
    }

}
